import React from "react";
import { View, TouchableOpacity, Text, Image, DatePickerAndroid, Platform } from "react-native";

import SizeUtils from "../../common/SizeUtils";
import ToastUtils from "../../common/ToastUtils";
import CommonStyles from "../../common/CommonStyles";
import ImageConstants from "../../common/ImageConstants";
import Config from "../../config";
import BasePage from "../common/BasePage";
import imagePicker from "react-native-image-picker";
import DataManager from "../../datas/DataManager";
import Constants from "../../common/Constants";
import UserUpdateSelfDataAction from "../../actions/user/UserUpdateSelfDataAction";
import ImagePickUtil from "../../utils/ImagePickUtil";
import ResponseConstants from "../../common/ResponseConstants";
import TImage from "../../components/TImage";
import TIcon from "../../components/TIcon";
import CommonShowPickerAction from "../../actions/common/CommonShowPickerAction";

export default class UserZiliaoPage extends BasePage {
  constructor(props) {
    super(props);

    this.state = {
      openImage: false,
      data: Constants.USER
    };
    this.avatarData = null;
  }

  _dealEnterPage() {
    this.state.data = Constants.USER;
  }

  shouldComponentUpdate(nextProps, nextState) {
    if (nextState.viewStatus == ResponseConstants.status_deal_success) {
      ToastUtils.show("修改成功");
      nextState.viewStatus = 1;
    }
    return true;
  }

  render() {
    return (
      <View
        style={[
          CommonStyles.page,
          {
            paddingTop: Config.paddingTop,
            flexDirection: "column",
            paddingLeft: SizeUtils.translateDesignWidthToCode(40),
            paddingRight: SizeUtils.translateDesignWidthToCode(40),
            backgroundColor: "#ffffff"
          }
        ]}
      >
        {this._renderHeadImage()}
        {this._renderItem(
          "昵称",
          this.state.data.nick || "",
          this._onPressNickName.bind(this, "nick"),
          "请输入昵称"
        )}
        {this._renderItem(
          "邮箱",
          this.state.data.email || "",
          this._onPressEmail.bind(this, "email"),
          "请输入邮箱"
        )}
        {this._renderItem(
          "性别",
          this.getGender(),
          this._onPressGender.bind(this),
          "请选择"
        )}
        {this._renderItem(
          "生日",
          this.state.data.birthday || "",
          this._onPressBirthday.bind(this),
          "请选择"
        )}
        {this._renderItem(
          "所在单位",
          this.state.data.department || "",
          this._onPressDepartment.bind(this, "department"),
          "请输入所在单位"
        )}
        {this._renderItem(
          "所在部门",
          this.state.data.section || "",
          this._onPressSection.bind(this, "section"),
          "请输入所在部门"
        )}
        {this._renderNavigationBar()}
      </View>
    );
  }

  _renderHeadImage() {
    return (
      <TouchableOpacity
        style={{
          flexDirection: "row",
          justifyContent: "space-between",
          alignItems: "center",
          paddingRight: SizeUtils.translateDesignWidthToCode(28),
          width:
            SizeUtils.getWindowSize().width -
            SizeUtils.translateDesignWidthToCode(28),
          height: SizeUtils.translateDesignHeightToCode(100),
          borderBottomWidth: SizeUtils.translateDesignHeightToCode(2),
          borderBottomColor: "#f2f2f2"
        }}
        onPress={this._showImage.bind(this)}
      >
        <Text
          style={{
            color: "#000000",
            fontSize: SizeUtils.translateFontSizeToCode(28)
          }}
        >
          头像
        </Text>
        <View style={{ flexDirection: "row", alignItems: "center" }}>
          <TImage
            source={this._getAvarta()}
            style={{
              width: 76,
              height: 76,
              borderRadius: 76,
              overflow: "hidden"
            }}
            isMini={true}
          />
          <TIcon
            name="ion|ios-arrow-forward-outline"
            size={20}
            color="#66686B"
            style={{
              marginLeft: SizeUtils.translateDesignWidthToCode(20),
              width: 20,
              height: 20
            }}
          />
        </View>
      </TouchableOpacity>
    );
  }

  _renderItem(title, desc, onPress, placeholder) {
    const showPlaceholder = desc === "";
    const descColor = showPlaceholder ? "#66686B" : "#000000";
    return (
      <TouchableOpacity
        style={{
          flexDirection: "row",
          justifyContent: "space-between",
          alignItems: "center",
          paddingRight: SizeUtils.translateDesignWidthToCode(28),
          width:
            SizeUtils.getWindowSize().width -
            SizeUtils.translateDesignWidthToCode(28),
          height: SizeUtils.translateDesignHeightToCode(100),
          borderBottomWidth: SizeUtils.translateDesignHeightToCode(2),
          borderBottomColor: "#f2f2f2"
        }}
        onPress={onPress}
      >
        <Text
          style={{
            color: "#000000",
            fontSize: SizeUtils.translateFontSizeToCode(28)
          }}
        >
          {title}
        </Text>
        <View style={{ flexDirection: "row" }}>
          <Text
            style={{
              color: descColor,
              fontSize: SizeUtils.translateFontSizeToCode(28),
              textAlign: "right"
            }}
          >
            {showPlaceholder ? placeholder : desc}
          </Text>
          <TIcon
            name="ion|ios-arrow-forward-outline"
            size={20}
            color="#66686B"
            style={{
              marginLeft: SizeUtils.translateDesignWidthToCode(20),
              width: 20,
              height: 20
            }}
          />
        </View>
      </TouchableOpacity>
    );
  }

  getGender() {
    if (this.state.data.gender && this.state.data.gender === 1) {
      return "男";
    }
    if (this.state.data.gender && this.state.data.gender === 2) {
      return "女";
    }
    return "";
  }

  _onPressNickName() {
    this.gotoPage(Config.pages.user_xgnc);
  }

  _onPressEmail() {
    this.gotoPage(Config.pages.user_xgemail);
  }

  _onPressDepartment() {
    this.gotoPage(Config.pages.user_xgdw);
  }

  _onPressSection() {
    this.gotoPage(Config.pages.user_xgbm);
  }

  _onPressGender() {
    const params = { pickerData: ["男", "女"] };
    new CommonShowPickerAction().call(this, {
      ...params,
      callback: (value, value1) => {
        this._editCallback(value, value1);
      }
    });
  }

  _editCallback(value, value1) {
    const gender = value === "男" ? 1 : 2;
    if (gender == Constants.USER.gender) {
      ToastUtils.show("性别没有变化!");
      return;
    }
    new UserUpdateSelfDataAction().call(this, {
      gender: gender
    });
  }

  _onPressBirthday() {
    if (Platform.OS === 'ios') {
      const params = { type: "date" };
      new CommonShowPickerAction().call(this, {
        ...params,
        callback: (value, value1) => {
          this._birthdayCallback(value, value1);
        }
      });
    }else{
        try {
            DatePickerAndroid.open({ date: new Date() }).then(({ action, year, month, day }) => {
              if (action !== DatePickerAndroid.dismissedAction) {
                this._editCallbackByAndroidPicker(new Date(year, month, day))
              }
            })
          } catch ({ code, message }) {
            console.log('Cannot open date picker', message)
          }
    }
  }
  _editCallbackByAndroidPicker(value){
    Date.prototype.Format = function(fmt) {
      //author: meizz
      var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        S: this.getMilliseconds() //毫秒
      };
      if (/(y+)/.test(fmt))
        fmt = fmt.replace(
          RegExp.$1,
          (this.getFullYear() + "").substr(4 - RegExp.$1.length)
        );
      for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
          fmt = fmt.replace(
            RegExp.$1,
            RegExp.$1.length == 1
              ? o[k]
              : ("00" + o[k]).substr(("" + o[k]).length)
          );
      return fmt;
    };
    const birthday = value.Format("yyyy-MM-dd");
    if (birthday === Constants.USER.birthday) {
      ToastUtils.show("年龄没有变化!");
      return;
    }
    new UserUpdateSelfDataAction().call(this, {
      birthday: birthday
    });
  }
  _birthdayCallback(value, value1) {
    Date.prototype.Format = function(fmt) {
      //author: meizz
      var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        S: this.getMilliseconds() //毫秒
      };
      if (/(y+)/.test(fmt))
        fmt = fmt.replace(
          RegExp.$1,
          (this.getFullYear() + "").substr(4 - RegExp.$1.length)
        );
      for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
          fmt = fmt.replace(
            RegExp.$1,
            RegExp.$1.length == 1
              ? o[k]
              : ("00" + o[k]).substr(("" + o[k]).length)
          );
      return fmt;
    };
    const birthday = new Date(value).Format("yyyy-MM-dd");
    if (birthday === Constants.USER.birthday) {
      ToastUtils.show("年龄没有变化!");
      return;
    }
    new UserUpdateSelfDataAction().call(this, {
      birthday: birthday
    });
  }

  _getAvarta() {
    if (this.state.avatar) {
      return { uri: "data:image/png;base64," + this.state.avatar };
    } else if (
      this.state.data &&
      this.state.data.avatar_url &&
      this.state.data.avatar_url != "http://beahan.org/lolita"
    ) {
      return { uri: this.state.data.avatar_url };
    } else {
      return ImageConstants.common_default_head2;
    }
  }

  _showImage() {
    ImagePickUtil.openImagePick(this.onUploadImage, this);
  }

  onUploadImage(response) {
    var key = Constants.RANDOM_UPLOAD_NAME(25) + response.fileName;
    DataManager.modelDic[Constants.MODULE_TYPE.ALI_OSS].uploadFile(
      key,
      response.uri,
      function(pre, res) {
        new UserUpdateSelfDataAction().call(this, {
          avatar_url: Config.aliUrl + pre + key
        });
      },
      this
    );
  }
}
